<?php

namespace App\Services\SettleGoldRecordReselling;

use App\Models\GoldSplit;
use Carbon\Carbon;
use App\Models\User;
use App\Models\GoldRecord;
use Illuminate\Support\Facades\DB;

class SettleGoldRecordReselling
{
	protected ?User $targetUser = null;

	protected GoldRecord $record;
	protected ?GoldRecord $upRecord = null;

    protected ?GoldSplit $needSettledSplit = null;


	public function __construct(GoldRecord $record)
	{
		$this->record = $record;
        $this->upRecord = $record->upGoldRecord;
		$this->targetUser = $record->upGoldRecord ? $record->upGoldRecord->user : null;
        $this->needSettledSplit = $record->needSettledSplit();
	}

	protected function shouldBeSettled(): bool
	{
		$upRecord = $this->upRecord;

        if ($this->needSettledSplit) return true;

        if (! $upRecord) {
            return false;
        } elseif ($upRecord->user->is_mock) {
            return false;
        } elseif ($upRecord->isFinished()) {
            return false;
        } elseif (!$this->targetUser) {
            return false;
        } else {
            return true;
        }
	}

    protected function endUpGoldRecord(GoldRecord $upRecord)
    {
        $upRecord->update(['finished_at' => Carbon::now()]);
        $upRecord->user->addRecordToFinishedCache($upRecord->cacheKey());
    }

	protected function settle()
	{
		DB::transaction(function () {

			$record = $this->record->fresh();

            if ($split = $this->needSettledSplit) {
                $split->settle($record);
                $upRecord = $split->splitRecord->refresh();
                if ($upRecord->isSplitSettled()) {
                    $this->endUpGoldRecord($upRecord);
                }
            } else {
                $upRecord = $record->upGoldRecord->refresh();
                $record->settle($upRecord);
                $this->endUpGoldRecord($upRecord);
            }

			$record->update(['settled_at' => Carbon::now()]);
		});
	}

	public function run()
	{
		if (! $this->shouldBeSettled()) return;

		$this->settle();
	}
}
